import { useState, useEffect } from 'react';
import { message, Modal } from 'antd';
import type { UploadListType } from 'antd/es/upload/interface';
import { ProFormUploadButton } from '@ant-design/pro-form';
import { UploadFile, DeleteFile } from '@/services/upload';
import { PlusOutlined } from '@ant-design/icons';

export default (props: any) => {
  const { title, initFileList, maxCount } = props;

  const [uploadedFileList, handleUploadedFileList] = useState([]);
  const [previewVisible, handlePreviewVisible] = useState(false);
  const [previewTitle, handlePreviewTitle] = useState('');
  const [previewImageUrl, handlePreviewImageUrl] = useState('');

  useEffect(() => {
    if (initFileList) {
      handleUploadedFileList(initFileList);
    }
    console.log('effect');
  }, [initFileList]);

  const handleChange = async ({ fileList }: any) => {
    handleUploadedFileList(fileList);
  };

  const uploadFile = async ({ onSuccess, onError, file }: any) => {
    try {
      console.log('upload file');
      const response = await UploadFile('illuminant', file);

      file.fid = response.data.fid;
      onSuccess(response, file);
    } catch (e) {
      onError(e);
    }
  };

  const previewFile = async (file: any) => {
    handlePreviewVisible(true);
    handlePreviewTitle(file.name);
    let src = file.url;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    handlePreviewImageUrl(src);
  };

  const removeFile = async (file: any) => {
    console.log('remove file');
    const response = await DeleteFile(file.fid);
    if (response.code === 10000) message.success('删除文件成功');
    else message.error('文件删除失败');
  };

  const listType: UploadListType = 'picture-card';
  const uploadProps = {
    name: 'file',
    title,
    fileList: uploadedFileList,
    listType,
    fieldProps: {
      maxCount,
      className: 'avatar-uploader',
      customRequest: uploadFile,
      onRemove: removeFile,
      onPreview: previewFile,
    },
  };

  return (
    <div>
      <ProFormUploadButton icon={<PlusOutlined />} {...uploadProps} onChange={handleChange} />
      <Modal
        visible={previewVisible}
        title={previewTitle}
        footer={null}
        onCancel={() => handlePreviewVisible(false)}
      >
        <img alt="preview" style={{ width: '100%' }} src={previewImageUrl} />
      </Modal>
    </div>
  );
};
